<?php
/**
 * Created by PhpStorm.
 * User: joe
 * Date: 18-9-26
 * Time: 上午8:55
 */

namespace App\Controllers;

use \App\Libraries\Datatable;

class Test extends Application {

    public function __construct(...$params) {
        parent::__construct(...$params);
        if (!$this->user) {
            $this->showError("用户尚未登录，请登录后重新打开。", site_url(''));
        }

    }

    function index($id = 0) {
        $id = $id ?: 1;
        $roomModel=new \App\Models\RoomModel();
        $room=$roomModel->find($id);
        $this->data['room']=json_encode($room);
        $page = new \App\Models\PageModel();
        $this->data['page'] = json_encode($page->find($room['page']));

        $this->render('front/test', '考试页面', '');
    }

    function page() {
        $type = $this->request->getPost('type');
        $category = $this->request->getPost('category');
        $num = $this->request->getPost("num");
        $upset = $this->request->getPost("upset");

        $categoryModel = new \App\Models\CategoryModel();
        $categories = $categoryModel->getChildren($category, 'id');

        $questionModel = new \App\Models\QuestionModel();

        $questions = $questionModel->random($categories, $type, $num);

        //打乱选项
        if ($upset && ($type == 1 || $type == 2)) {
            for ($i = 0; $i < count($questions); $i++) {
                $option = json_decode($questions[$i]['option'], true);
                shuffle($option);
                $questions[$i]['option'] = json_encode($option);
            }
        }
        $this->showJson($questions);
    }

    public function records() {
        $this->render('front/record', '考试记录');
    }

    //获取历史记录
    public function record() {
        $table = $this->request->getGet();
        //$user = $this->request->getPost('user')?;
        $test = new Datatable('test');

        if (isset($table['sort'])) {
            $test->orderBy($table['sort'], $table['order']);
        }

        if (isset($table['limit'])) {
            $test->limit($table['limit'], $table['offset']);
        }

        $testList = $test->select('test.*,room.name as roomName')
                         ->where("test.user", $this->user['id'])
                         ->join("room", "room.id=test.room")
                         ->json();

        echo $testList;
    }

    public function rank() {
        $user = $this->request->getPostGet('user');
        $room = $this->request->getPostGet('room');
        $page = $this->request->getPostGet('page');
        $limit = $this->request->getPostGet('limit');

        $testModel = new \App\Models\TestModel();

        if ($user) {
            $rank = $testModel->findUserRank($room, $page, $user);
        } else {
            $rank = $testModel->rank($room, $page);
        }
        $this->showJson($rank);
    }
}